import {Document, Progress, UserGroup, Task, Group, User} from '../../models'
import * as $group from '../../services/group'
import JOBS from '../../jobs'
import fdb from '../../lib/fdb'
import dayjs from 'dayjs'
module.exports = {
  title: '给参与人员发通知',
  enable: true,
  async run ({taskId}) {
    let task = await Task.findById(taskId)
    if (!task) return
    if (!task.groupId) return
    let document = await Document.findById(task.versionId)
    let title = document ? document.name : ''
    if (!title) return
    let group = await Group.findById(task.groupId)
    let groupName = group.name || '未知班级'
    let user = await User.findById(task.ownerId)
    let userName = user.nickName || '未知老师'
    let progresses = await fdb.findAll({
      tbl: 'progresses as p',
      joins: [
        'left join users as u on u.id = p.userId',
        'left join user_group as ug on ug.userId = p.userId and ug.groupId=p.groupId'
      ],
      attrs: [
        'p.*, ug.name as memberName, u.nickName as memberNickName, u.avatarUrl as memberAvatarUrl, u.gender as memberGender'
      ],
      where: [
        `p.taskId=${task.id} and p.groupId=${task.groupId}`
      ],
      orders: [
        `createdAt desc`
      ],
      log: true
    })
    progresses.forEach(n => {
      let url = 'pages/progress/main?isShowSideMenu=y&progressId=' + n.id
      if (n.type === 'exercise') {
        if (!n.documentId) return
        if (!n.groupId) return
        url = `pages/homework-detail/main?agid=${n.documentId}_${n.groupId}&isShowSideMenu=y`
      }
      let notifyData = {
        title: '作业通知',
        data: {
          keyword1: {
            value: title
          },
          keyword2: {
            value: userName
          },
          keyword3: {
            value: dayjs().format('YYYY-MM-DD HH:mm:ss')
          }
        },
        url
      }
      // let notifyData = {
      //   title: '作业未完成提醒',
      //   data: {
      //     keyword1: {
      //       value: title
      //     },
      //     keyword2: {
      //       value: groupName
      //     },
      //     keyword3: {
      //       value: userName
      //     },
      //     keyword4: {
      //       value: dayjs().format('YYYY-MM-DD HH:mm:ss')
      //     }
      //   },
      //   url: '/pages/progress/main?isShowSideMenu=y&progressId=' + n.id
      // }
      JOBS.add('send-notify-to-user', {userId: n.userId, notifyData})
    })
  }
}
